<template>
  
  <view class="index">
    <view class="content">
      <view v-for="(item, index) in messages" :key="index" class="content__text" :class="item.role">
        <!-- 判断item.content的类型是 集合还是字符串 -->
        <view v-if="typeof item.content === 'object'">
          <view v-for="(content, index) in item.content" :key="index">
            <view v-if="content.type === 'text'">
              {{content.text}}
            </view>
            <view v-else-if="content.type === 'image_url'">
              <image :src="content.image_url.url" mode="aspectFit" @bindtap="previewImg('{{ content.image_url.url }}')" style="width: 100%;height: 100px;"/>
            </view>
          </view>
        </view>
        <view v-else>
          {{item.content}}
        </view>
      </view>

    </view>
    <view class="input" :bottom="true">
      <nut-input  v-model="inputMsg" placeholder="请输入问题内容或者拍照" clearable center  >
        <template #button>
          <nut-button shape="square" plain  type="primary" @click="sendMessage()">发送</nut-button>
          <nut-button shape="square" plain  type="primary" @click="showCamera = true">拍照</nut-button>
        </template>
      </nut-input>
      
    </view>
    <nut-toast :msg="msg" v-model:visible="show" :type="type" :cover="cover" />
    <nut-popup position="bottom" closeable round :style="{ height: '95vh' }" v-model:visible="showCamera" :close-on-click-overlay="false">
      <div class="wrapper">
        <div class="content">
          <camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 100%;"></camera>
          <nut-grid :gutter="10" style="z-index: 999;position: fixed;bottom: 18vh;background-color: rgba(0, 0, 0, 0.1); ">
            <nut-grid-item 
            v-for="(item, index) in images" :key="index"
            style="background-color: rgba(0, 0, 0, 0.1);padding: 0;"
            >
              <nut-avatar
                size="large"
                shape="square"
                :url="item"
                bg-color="rgba(0, 0, 0, 0.1)"
              />
            </nut-grid-item>
          </nut-grid>
          <nut-button shape="square" plain type="primary" style="position: fixed;left:20vw; bottom: 8vh;z-index: 999;" @click="takePhoto()">拍照</nut-button>
          <nut-button shape="square" plain type="success" style="position: fixed;left:60vw;bottom: 8vh;z-index: 999;" @click="showCamera=false;">确认</nut-button>
        </div>
      </div>
    </nut-popup>


  </view>
</template>

<script>
import { reactive, toRefs } from 'vue';
import Taro from '@tarojs/taro';
export default {
  name: 'Index',
  components: {
    
  },
  setup(){
    const cameraContext = Taro.createCameraContext()
    const state = reactive({
      msg: '欢迎使用 NutUI3.0 开发小程序',
      msg2: '你成功了～',
      type: 'text',
      inputMsg: '',
      images:[],      
      messages: [
        {
          role: 'user',
          content: "你是谁?"

        },
        {
          role: 'assistant',
          content: '我是你的个人助理，可以分析图片，帮你看世界'
        } 
      ],
      show: false,
      showCamera: false,
      cover: false
    });

    const previewImg = (url) => {
      let urls=[]
      state.messages.forEach((item) => {
        
        if (typeof item.content === 'object') {
          item.content.forEach((img) => {
            if (img.type === 'image_url') {
              urls.push(img.image_url.url)
            }
          })
        }
        
      })

      console.log(urls)


      Taro.previewImage({
        current: url,
        urls: urls
      })
    }

    const takePhoto = (e) => {
      console.log(state.images)
      if (state.images.length >= 3) {
        handleClick('text', '最多上传3张图片', true)
        return
      } 
      cameraContext.takePhoto({
        quality: 'normal',
        success: (res) => {
          console.log(res)
          Taro.getFileSystemManager().readFile({
            filePath: res.tempImagePath,
            encoding: 'base64',
            success: (result)=>{
              const base64='data:image/png;base64,'+result.data
              state.images.push(base64)
            },
            fail: (err)=>{
              console.log('读取图片失败',err)
            }
          });

          
        }
      })
    }

    const handleClick = (type, msg, cover = false) => {
      state.show = true;
      state.msg = msg;
      state.type = type;
      state.cover = cover;
    };

    const sendMessage=()=>{
      console.log('发送消息')
      let content = state.inputMsg
      let currentMultiContent=[]
      if (content.length<=0) {
        if (state.images.length <= 0) {
          handleClick('text', '请输入问题内容或者拍照', true)
          return
        }
        content = "这是什么？"
      }

      if (state.images.length > 0) {
        currentMultiContent.push({
          type: 'text',
          text: content
        })

        state.images.forEach((item) => {
          currentMultiContent.push({
            type: 'image_url',
            image_url: {
              url: item,
              detail: "high"
            }
          })
        })

        content=currentMultiContent
      }
      state.messages.push({
            role: 'user',
            content: content,
          })
      // const BaseHost = process.env.API_BASE_URL
      // const OpenAIKey = process.env.OPENAI_KEY
      const BaseHost='https://ai-pool-api-pro-test-3.apisix.xthktech.cn'
      const OpenAIKey='sk-zEvzpPYdj7fgHizZB1E97dD7887a458aB95c6aC1D19bFcDe-33'

      console.log(BaseHost)
      // 清除输入框内容
      state.inputMsg = ''
      state.images = []


      const requestTask= Taro.request({
        method: 'POST',
        url: BaseHost+'/v1/chat/completions',
        data: {
            "messages": state.messages,
            "stream": false,
            "model": "gpt-4o",
            "temperature": 0.5,
            "presence_penalty": 0,
            "frequency_penalty": 0,
            "top_p": 0.5
        },
        header: {
          'content-type': 'application/json',
          'Accept': 'text/event-stream',
          'Authorization': 'Bearer '+OpenAIKey
        },
        // enableChunked: true,
        success: function (res) {
          // requestTask.abort()
          console.log(res.data)
          console.log("===============success===========")
          if ('error' in res.data) {
            state.messages.push({
              role: 'assistant',
              content: "请求失败，请稍后重试，失败原因："+res.data.error.code
            })
            return
          }
          
          if ('choices' in res.data) {
            res.data.choices.forEach((item) => {
              state.messages.push(item.message)
            })
          }

        },
        fail: function (error) {
          console.log("===============fail===========")
          console.log(error)
          Taro.showToast({
            title: error.errMsg=='request:fail timeout'?'请求超时，请检查网络':'请求失败，请稍后重试',
            icon: 'none',
            duration: 2000
          })
          state.messages.push({
            role: 'assistant',
            content: "请求失败，请稍后重试"          
          })

        }
      })

      // requestTask.onHeadersReceived((res) => {
      //   console.log('onHeadersReceived', res)
      // })
      // requestTask.onChunkReceived((res) => {
      //   console.log('onChunkReceived', res)
      // })



    }

    return {
      ...toRefs(state),
      handleClick,
      sendMessage,
      takePhoto,
      previewImg
    }
  }
}
</script>

<style lang="scss">
.index {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
}
.wrapper {
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: center;
  .content {
    display: flex;
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 8px;
    align-items: center;
    justify-content: center;
    color: red;
  }
  .nut-grid-item__content{
    padding: 0;
  }
}
.content {
  padding-bottom: 10vh;
  height: 100vh;
  overflow-y: scroll;
  width: 100%;
  // border: 1px solid #000;
}
.input{
  z-index: 999;
  position: fixed;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #000;
}
.content__text {
  padding: 10px;
  margin: 10px;
  border-radius: 10px;
  display: inline-block;
  width: 51vw;
  position: relative  ;
  top: 10;
  font-size: 0.8rem;

}
.assistant {
  background-color: #f0f0f0;
  text-align: left;
  left: -20vw;
  
}
.user {
  background-color: #89D961;
  text-align: right;
  right: 0;
  left: 20vw;
} 
</style>
